<?php 

// Example
//php5 /var/www/workspace/blooglebot/bot/sitemap_generator.php it


session_start();

$dirname = dirname(__FILE__);
require_once($dirname.'/../config.php');
require_once($dirname.'/lib/sitemaplib.php');

// Get php client language
foreach ($CONFIG->availablelanguages as $lang) {
	if (isset($argv[1]) && $argv[1] == $lang) {
		$_SESSION['lang'] = $lang;
	}
}

if (empty($_SESSION['lang'])) {
    die('No language specified');
}

die('REPLACE CONFIG->webdir!!!!');
$CONFIG->webdir = '';

// Language specific DB instance
$DB_LANG = new DB_lang();

$output = new output_manager();

$timestart = time();

// Converting urls to XMLs
$i = 0;
$nfile = 0;
$filepath = $CONFIG->datadir.'/sitemaps/'.$_SESSION['lang'].'/sitemap_'.$nfile.'.xml';
$xmlstring = '<?xml version="1.0" encoding="UTF-8"?>'.LB.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.LB;
echo 'Memory usage -> init'.LB;

// Getting all the site labels ordered by label name to be able to discard repeated relations
$sql = "SELECT DISTINCT labelid FROM entrylabels el ORDER BY labelid DESC";
$labels = $DB_LANG->selectResponses($sql);

// Getting allll the site urls
foreach ($labels as $label) {

    // Adding the label
    $xmlstring.= '  <url>'.LB;
    $xmlstring.= '    <loc>'.$output->link_output(decode_text($label->labelid)).'</loc>'.LB;
    $xmlstring.= '    <lastmod>'.strftime('%Y-%m-%d').'</lastmod>'.LB;
    $xmlstring.= '    <changefreq>monthly</changefreq>'.LB;
    $xmlstring.= '    <priority>1</priority>'.LB;
    $xmlstring.= '  </url>'.LB;

    $i++;

    // The maximum number of urls in a XML is 50000 and 10M (with 499999 it reach 10MB) 
    if ($i == 45000) {
        add_sitemap($xmlstring, $filepath, $i, $nfile);
    }
    
    // Adding the related labels
    $labels = array($label->labelid);
    add_related($labels, 1, $xmlstring, $filepath, $i, $nfile, $output);
}

add_sitemap($xmlstring, $filepath, $i, $nfile);


// Let's create the sitemapindex
$filepath = $CONFIG->datadir.'/sitemaps/'.$_SESSION['lang'].'/siteindex.xml';
$xmlstring = '<?xml version="1.0" encoding="UTF-8"?>'.LB.'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.LB;
for ($i = 0; $i < $nfile; $i++) {
    $xmlstring.= '  <sitemap>'.LB;
    $xmlstring.= '    <loc>'.$CONFIG->webdir.'/sitemaps/'.$_SESSION['lang'].'/sitemap_'.$i.'.xml</loc>'.LB;
    $xmlstring.= '    <lastmod>'.strftime("%Y-%m-%d").'</lastmod>'.LB;
    $xmlstring.= '  </sitemap>'.LB;
}
$xmlstring.= '</sitemapindex>';

create_sitemap($filepath, $xmlstring);


$timeend = time();
echo date('i:s', $timeend - $timestart).' mins:secs'.LB;

echo 'Memory usage -> ending'.LB;

